import 'dart:ui';

import 'package:flutter/material.dart';
import 'package:flutter_oss_aliyun/flutter_oss_aliyun.dart';
import 'package:fusion_one/Utils/colorUtils.dart';
import 'package:fusion_one/dtos/file.dart';
import 'package:fusion_one/dtos/stage.dart';
import 'package:fusion_one/http/api.dart';
import 'package:fusion_one/view/components/image.dart';
import 'package:fusion_one/view/components/imagePreview.dart';
import 'package:fusion_one/view/components/stageList.dart';
import 'package:ls_loading/Type.dart';
import 'package:ls_loading/ls_loading.dart';

import '../../dtos/patientList.dart';

class PatientDetail extends StatefulWidget {
  Patient? patient;
  List<Stage> stages = [];

  PatientDetail({required this.patient, required this.stages});

  @override
  _patientState createState() => _patientState();
}

class _patientState extends State<PatientDetail> {
  String url = "";
  // 当前选中阶段
  Stage? activeStage;
  // 选中阶段的文件列表
  List<File> stageFiles = [];
  // 当前预览图片列表
  List<File> previewList = [];

  @override
  didUpdateWidget(PatientDetail oldWidget) {
    super.didUpdateWidget(oldWidget);
    if (oldWidget.patient?.avatar != widget.patient?.avatar) {
      if (widget.patient?.avatar != null) {
        Client()
            .getSignedUrl(widget.patient!.avatar!,
                process: "image/resize,w_150")
            .then((value) {
          setState(() {
            this.url = value;
          });
        });
      }
    }
    if (oldWidget.patient?.id != widget.patient?.id) {
      setState(() {
        stageFiles = [];
        activeStage = null;
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(children: [
        Container(
          padding: const EdgeInsets.all(50),
          height: 300,
          child: Row(
            children: [
              Container(
                alignment: Alignment.center,
                width: 150,
                height: 250,
                margin: const EdgeInsets.only(right: 50),
                decoration: BoxDecoration(
                  color: widget.patient?.avatar == null && url == ""
                      ? const Color.fromARGB(255, 225, 225, 225)
                      : const Color.fromARGB(255, 255, 255, 255),
                  // borderRadius: BorderRadius.all(Radius.circular(10))
                ),
                child: widget.patient?.avatar != null
                    ? (url == ""
                        ? LsLoading(
                            style: LoadingStyle(
                                color: Colors.blue,
                                strokeWidth: 5,
                                radius: 30,
                                width: 150,
                                height: 150))
                        : FadeInImage(
                            placeholder:
                                const AssetImage("images/Renxiang.png"),
                            image: NetworkImage(url),
                            fadeOutDuration: const Duration(milliseconds: 1),
                            fadeInDuration: const Duration(milliseconds: 1),
                            width: 150,
                            // fit: BoxFit.fitWidth,
                          ))
                    : Image.asset(
                        'images/Renxiang.png',
                        width: 150,
                      ),
              ),
              Expanded(
                  child: Container(
                      alignment: Alignment.topCenter,
                      child: Wrap(
                        spacing: 8.0,
                        runSpacing: 8,
                        children: [
                          Container(
                            width: 300,
                            height: 30,
                            child: Text('患者ID：${widget.patient?.id ?? ""}'),
                          ),
                          Container(
                            width: 300,
                            height: 30,
                            child:
                                Text('姓名：${widget.patient?.patientName ?? ""}'),
                          ),
                          Container(
                            width: 300,
                            height: 30,
                            child: Text('年龄：${widget.patient?.age ?? ""}'),
                          ),
                          Container(
                            width: 300,
                            height: 30,
                            child: Text(
                                '当前阶段：${widget.patient?.stageTypeName ?? ""}'),
                          ),
                          Container(
                            width: 300,
                            height: 30,
                            child: Text(
                                '牙龄：${widget.patient?.dentalAge != null ? widget.patient?.dentalAge == '1' ? '替牙期' : widget.patient?.dentalAge == '2' ? "恒牙期" : "" : ''}'),
                          ),
                          Container(
                            width: 300,
                            height: 30,
                            child: Text(
                                '就诊时间：${widget.patient?.tegistrationtime ?? ""}'),
                          ),
                          Container(
                            width: double.infinity,
                            height: 30,
                            child: Wrap(
                              children: [
                                const Text('标签：'),
                                ...widget.patient != null
                                    ? widget.patient!.tagInfo
                                        .map((e) => Container(
                                              margin: const EdgeInsets.only(
                                                  right: 10),
                                              padding:
                                                  const EdgeInsets.fromLTRB(
                                                      5, 2, 5, 2),
                                              decoration: BoxDecoration(
                                                  color: HexColor(e.color),
                                                  borderRadius:
                                                      const BorderRadius.all(
                                                          Radius.circular(5))),
                                              child: Text(
                                                e.text,
                                                style: TextStyle(
                                                  color: HexColor(e.forecolor),
                                                  fontSize: 12,
                                                ),
                                              ),
                                            ))
                                        .toList()
                                    : []
                              ],
                            ),
                          ),
                        ],
                      )))
            ],
          ),
        ),
        Container(
          height: 1,
          color: const Color.fromARGB(115, 97, 97, 97),
        ),
        Container(
          padding: const EdgeInsets.all(30),
          child: Column(children: [
            Container(
              alignment: Alignment.topLeft,
              margin: const EdgeInsets.only(bottom: 20),
              child: const Text(
                '治疗阶段',
                style: TextStyle(fontSize: 20),
              ),
            ),
            SizedBox(
              width: double.infinity,
              height: 50,
              child: ListView(
                scrollDirection: Axis.horizontal,
                children: widget.stages
                    .map(
                      (stage) => StageWidget(
                        stage: stage,
                        activeStage: activeStage,
                        onClick: (stage) async {
                          setState(() {
                            activeStage = stage;
                            stageFiles = [];
                          });
                          // 请求阶段文件列表
                          var files = await Api.queryStageFileList(
                              stageId: stage.id,
                              // 处理未分类传入的参数
                              pid:
                                  stage.id == '20' ? widget.patient?.id : null);
                          setState(() {
                            stageFiles = files;
                            // 设置预览列表，stl文件不显示
                            previewList = files
                                .where((element) => !element.isSTL)
                                .toList();
                          });
                        },
                      ),
                    )
                    .toList(),
              ),
            )
          ]),
        ),
        Expanded(
            child: Container(
          padding: const EdgeInsets.all(30),
          child: ListView(children: [
            Wrap(
              alignment: WrapAlignment.start,
              children: [
                ...stageFiles.asMap().entries.map((entry) {
                  int index = entry.key;
                  File value = entry.value;

                  return Container(
                    margin: const EdgeInsets.only(bottom: 30, right: 10),
                    child: LsImage(
                      fileId: value.fileId,
                      onClick: () async {
                        showDialog(
                            context: context,
                            builder: (context) {
                              return ImagePreview(
                                index: index,
                                images: previewList,
                              );
                            });
                      },
                    ),
                  );
                }).toList(),
              ],
            )
          ]),
        ))
      ]),
    );
  }
}
